package com.ruoyi.littleRedBook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.littleRedBook.domain.pojo.ChatMessage;
import com.ruoyi.littleRedBook.domain.pojo.User;
import com.ruoyi.littleRedBook.mapper.ChatMessageMapper;
import com.ruoyi.littleRedBook.mapper.UserMapper;
import com.ruoyi.littleRedBook.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChatServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private UserMapper userMapper;

    private Long getCurrentUserId() {
        return 1L; // 替换为真实当前用户ID获取逻辑
    }

    @Override
    public AjaxResult sendMessage(ChatMessage message) {
        Long senderId = getCurrentUserId();
        Long receiverId = message.getReceiverId();

        // 校验接收者存在
        User receiver = userMapper.selectById(receiverId);
        if (receiver == null) {
            return AjaxResult.error("接收用户不存在");
        }

        // 填充消息信息
        ChatMessage newMessage = new ChatMessage();
        newMessage.setSenderId(senderId);
        newMessage.setReceiverId(receiverId);
        newMessage.setProductId(message.getProductId()); // 可选关联商品
        newMessage.setMessageType(message.getMessageType() == null ? 1 : message.getMessageType()); // 默认文本
        newMessage.setContent(message.getContent());
        newMessage.setIsRead(0); // 初始未读
        newMessage.setCreatedAt(LocalDateTime.now());

        int rows = chatMessageMapper.insert(newMessage);
        return rows > 0 ? AjaxResult.success("消息发送成功", newMessage) : AjaxResult.error("消息发送失败");
    }

    @Override
    public AjaxResult getChatHistory(Long otherUserId, Integer pageNum, Integer pageSize) {
        Long currentUserId = getCurrentUserId();
        // 校验对方用户存在
        User otherUser = userMapper.selectById(otherUserId);
        if (otherUser == null) {
            return AjaxResult.error("对方用户不存在");
        }

        Page<ChatMessage> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        // 筛选条件：(我发的给对方) 或 (对方发的给我)
        queryWrapper.and(w -> w.eq("sender_id", currentUserId).eq("receiver_id", otherUserId)
                              .or().eq("sender_id", otherUserId).eq("receiver_id", currentUserId))
                    .orderByAsc("created_at"); // 按时间正序（旧消息在前）

        Page<ChatMessage> messagePage = chatMessageMapper.selectPage(page, queryWrapper);

        // 自动标记对方发来的消息为已读
        chatMessageMapper.markReadBySenderAndReceiver(otherUserId, currentUserId);

        return AjaxResult.success(messagePage.getRecords());
    }

    @Override
    public AjaxResult markMessagesAsRead(Long otherUserId) {
        Long currentUserId = getCurrentUserId();
        int rows = chatMessageMapper.markReadBySenderAndReceiver(otherUserId, currentUserId);
        return AjaxResult.success("成功标记" + rows + "条消息为已读");
    }

    @Override
    public AjaxResult getUnreadCount(Long otherUserId) {
        Long currentUserId = getCurrentUserId();
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sender_id", otherUserId)
                    .eq("receiver_id", currentUserId)
                    .eq("is_read", 0);
        Long count = chatMessageMapper.selectCount(queryWrapper);
        return AjaxResult.success(count);
    }

    @Override
    public AjaxResult getContacts() {
        Long currentUserId = getCurrentUserId();
        // 获取所有与当前用户有过聊天的用户ID
        List<Long> contactIds = chatMessageMapper.selectContactIds(currentUserId);
        List<Object> contacts = new ArrayList<>();

        for (Long contactId : contactIds) {
            User user = userMapper.selectById(contactId);
            if (user == null) continue;

            // 查询最后一条消息
            ChatMessage lastMsg = chatMessageMapper.selectLastMessage(currentUserId, contactId);
            // 查询未读消息数量
            int unreadCount = Math.toIntExact(chatMessageMapper.selectCount(
                    new QueryWrapper<ChatMessage>()
                            .eq("sender_id", contactId)
                            .eq("receiver_id", currentUserId)
                            .eq("is_read", 0)
            ));


            Map<String, Object> contactInfo = new HashMap<>();
            contactInfo.put("userId", contactId);
            contactInfo.put("nickname", user.getNickname());
            contactInfo.put("avatar", user.getAvatar());
            contactInfo.put("lastMsg", lastMsg != null ? lastMsg.getContent() : "");
            contactInfo.put("lastTime", lastMsg != null ? lastMsg.getCreatedAt() : null);
            contactInfo.put("unreadCount", unreadCount);

            contacts.add(contactInfo);
        }

        return AjaxResult.success(contacts);
    }
}
